﻿using MoneyWentWhere.Utils.Storage;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace MoneyWentWhere.DataModel.Storage
{
    public static class MwwFileFormats
    {
        public static readonly FileFormat<MoneyDataSet> Excel2007 = new Excel2007Format();
        
        public static readonly FileFormat<MoneyDataSet> NativeXml = new XmlDataContractFormat<MoneyDataSet>();
        public static readonly EncryptedFormat<MoneyDataSet> EncryptedXml = 
            new EncryptedFormat<MoneyDataSet>(NativeXml, "Encrypted MWW 1.1");

        public static readonly FileFormat<MoneyDataSet> Csv = new CsvFormat();
        public static readonly EncryptedFormat<MoneyDataSet> EncryptedCsv = 
            new EncryptedFormat<MoneyDataSet>(Csv, "Encrypted MWW 1.1");

        public static FileFormat<MoneyDataSet> GetOpenFileFormat(String filename)
        {
            String ext = Path.GetExtension(filename).ToLowerInvariant();
            switch (ext)
            {
                case ".xlsx": return Excel2007;
                case ".mww":
                    if (EncryptedXml.ContainsHeader(filename))
                    {
                        return EncryptedXml;
                    }
                    return NativeXml;
                case ".csv":
                    if (EncryptedCsv.ContainsHeader(filename))
                    {
                        return EncryptedCsv;
                    }
                    return Csv;

                default:
                    throw new NotSupportedException("Unknown format: " + filename);
            }
        }

        public static FileFormat<MoneyDataSet> GetSaveFileFormat(String filename, String password)
        {
            String ext = Path.GetExtension(filename).ToLowerInvariant();
            switch (ext)
            {
                case ".xlsx": return Excel2007;
                case ".mww":
                    if (!String.IsNullOrEmpty(password))
                    {
                        return EncryptedXml;
                    }
                    return NativeXml;
                case ".csv":
                    if (!String.IsNullOrEmpty(password))
                    {
                        return EncryptedCsv;
                    }
                    return Csv;

                default:
                    throw new NotSupportedException("Unknown format: " + filename);
            }
        }

    }
}
